package com.powervision.sharesdkdemo.utils;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.huawei.hms.framework.common.Logger;
import com.powervision.sharesdkdemo.app.MyApp;

import java.io.File;

/**
 * @auth: njb
 * @date: 2021/10/18 16:04
 * @desc: 描述
 */
public class FileUtils {
    /**
     * 获取视频Uri
     *
     * @param path 文件路径
     * @return uri
     */
    public static Uri getVideoUri(String path) {
        Cursor cursor =
                MyApp.getInstance().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Video.Media._ID}, MediaStore.Video.Media.DATA + "=?",
                        new String[]{path}, null);
        Uri uri = null;

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID));
                Uri baseUri = Uri.parse("content://media/external/video/media");
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            cursor.close();
        }

        //如果获取失败，则使用此方法
        if (uri == null) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Video.Media.DATA, path);
            uri = MyApp.getInstance().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
        }
        if (uri == null) {
            uri = FileProvider.getUriForFile(MyApp.getInstance(),
                    MyApp.getInstance().getPackageName() + ".fileprovider", new File(path));
        }
        return uri;
    }

    public static Uri getUriFromPath(String path) {
        File file = new File(path);
        if (file.exists()) {
            return getUriFromFile(file);
        } else {
            Log.e("file","File is not exist");
            return null;
        }
    }
    public static Uri getUriFromFile(File file) {
        Uri mUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mUri = FileProvider.getUriForFile(MyApp.getInstance(),
                    MyApp.getInstance().getPackageName() + ".provider", file);
        } else {
            mUri = Uri.fromFile(file);
        }
        return mUri;
    }
}
